# coding:utf-8
# @Time : 2021/5/5 15:51 
# @Author : minuy
# @File : auth.py

from flask import url_for, redirect, flash, render_template, request, session
from flask_login import login_user, current_user, logout_user
from app.forms.auth import LoginForm
from app.models.user import User
from . import web


@web.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        print('收到登录请求')
        if form.captcha.data.lower() == str(session.get('captcha')).lower():
            user = User.query.filter_by(username=form.username.data).first()
            if user and user.check_password(form.password.data):
                if user.is_admin:
                    print('登录成功！', user.username)
                    login_user(user)
                    print('跳转', url_for('web.index'))
                    return redirect(url_for('web.index'))
                else:
                    print('不是管理员', user.username)
                    flash('无权限访问', category='error')
            else:
                print('登录失败！')
                flash('账号或密码错误', category='error')
        else:
            print('验证码错误', form.captcha.data.lower(), str(session.get('captcha')).lower())
            flash('验证码错误', category='error')
    elif current_user:
        print(current_user)
        logout_user()
        print('已经退出登录')
    return render_template('auth/login.html', form=form)
